//
//  BrowseView.swift
//  MagaCore
//
//  Created by wealon on 2024.
//  MagaCore.
//


import SwiftUI
import Combine
import SDWebImageSwiftUI

// 定义一个自定义的 PreferenceKey
struct ScrollOffsetPreferenceKey: PreferenceKey {
    static var defaultValue: CGFloat = 0
    
    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
        value = nextValue()
    }
}

struct HTBrowseView: View {
    @State private var scrollOffset: CGFloat = 0
    @State private var var_is_all_conditions = false
    var body: some View {
        VStack {
            // 导航
            HStack(spacing: 10) {
                HStack {
                    Image("search_btn")
                        .resizable()
                        .frame(width: 12, height: 12)
                    Text("one piece: clockwork island")
                        .font(.system(size: 12))
                        .foregroundColor(Color(hex:"#393939"))
                    Spacer()
                }
                .padding(.horizontal, 12)
                .frame(maxWidth: UIScreen.main.bounds.width)
                .frame(height: 36)
                .background {
                    Color(hex: "#000000").opacity(0.04)
                }
                .cornerRadius(18)
                
                Button(action: {}, label: {
                    Image("share_black")
                })
            }
            .padding(.bottom, 6)
            .padding(.horizontal, 14)
            .frame(width: UIScreen.main.bounds.width)
            // ALL标签
            HStack {
                Text("ALL")
                    .font(.system(size: 14, weight: .bold))
                    .padding(.top, 13)
                Spacer()
            }
            .padding(.horizontal, 14)
            ZStack(alignment: .top) {
                // 筛选 + 结果
                ScrollView(.vertical) {
                    VStack(spacing: 14) {
                        HTScreenConditions(conditions: ["all type", "series","all type", "series","all type", "series","all type", "series"])
                        HTScreenConditions(conditions: ["all type", "series"])
                        HTScreenConditions(conditions: ["all type", "series"])
                        HTScreenConditions(conditions: ["all type", "series"])
                        HTScreenConditions(conditions: ["all type", "series"])
                    }
                    .background(GeometryReader { geometry -> Color in
                        DispatchQueue.main.async {
                            self.scrollOffset = -geometry.frame(in: .named("scrollView")).origin.y
                        }
                        return Color.clear
                    })
                    
                    LazyVGrid(columns: Array(repeating: .init(.flexible()), count: 3), spacing: 4, content: {
                        ForEach(0..<25, id:\.self) { index in
                            HTBrowseItemView()
                        }
                    })
                }
                .padding(.horizontal, 14)
                
                if var_is_all_conditions {
                    HStack(content: {
                        Text("all genres · popular · release · animation")
                            .font(.system(size: 12, weight: .regular))
                            .foregroundColor(Color(hex: "#FF6C3C"))
                    })
                    .frame(width: UIScreen.main.bounds.width, height: 36)
                    .background {
                        Color(hex:"#F8F8F8")
                    }
                }
            }
        }
        .background(content: {
            Color(hex: "#F8F8F8")
        })
        .onReceive(Just(scrollOffset), perform: { offset in
            print("offset = \(offset)")
            let y = -148 + 26*5+14*4
            if offset >= CGFloat(y) {
                var_is_all_conditions = true
            } else {
                var_is_all_conditions = false
            }
        })
    }
}

struct HTScreenConditions: View {
    @State var selectIndex: Int = 0
    let conditions: [String]
    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: 10) {
                ForEach(conditions.indices, id: \.self) { index in
                    Text(conditions[index])
                        .font(getFont(index))
                        .foregroundColor(getTextColor(index))
                        .padding(.vertical, 6)
                        .padding(.horizontal, 8)
                        .background {
                            selectIndex == index ?
                            Color(hex: "#FF6C3C").opacity(0.2):Color.clear
                        }
                        .cornerRadius(4)
                        .onTapGesture {
                            self.selectIndex = index
                        }
                }
            }
        }
    }
    
    func getFont(_ index: Int) -> Font {
        if index == self.selectIndex {
            return .system(size: 12, weight: .bold)
        } else {
            return .system(size: 12)
        }
    }
    func getTextColor(_ index: Int) -> Color {
        if index == self.selectIndex {
            return Color(hex: "#FF6C3C")
        } else {
            return Color(hex: "#393939")
        }
    }
}


struct HTBrowseItemView: View {
    var body: some View {
        VStack(alignment: .leading) {
            WebImage(url: URL(string: "http://gips3.baidu.com/it/u=3557221034,1819987898&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960"))
                .resizable()
            
            Text("one piece: clockwork island ")
                .lineLimit(2)
                .font(.system(size: 12, weight: .bold))
                .padding(.bottom, 4)
            
            HStack(alignment: .top) {
                Text("dub · airing")
                    .font(.system(size: 10, weight: .black))
                    .foregroundColor(Color(hex: "#FF6C3C"))
                Spacer()
                Button(action: {}, label: {
                    Image("add_icon")
                        .frame(width: 20, height: 17)
                })
            }
        }
        .frame(height: 221)
        .background(content: {
            Color.white
        })
        .cornerRadius(5)
    }
}

#Preview {
    HTBrowseView()
}
